﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;

using CustomsSystem.BLL;
using CustomsSystem.Model;
using System.Collections.Generic;
using Maticsoft.Common;

namespace WEB.sheetInfo
{

    public partial class sheetEdit : System.Web.UI.Page
    {
        DataSet ds;
        SheetInfoManage bll = new SheetInfoManage();
        protected void Page_Load(object sender, EventArgs e)
        {
            #region 页面载入

            if (!Page.IsPostBack)
            {
                #region 页面载入-基础信息载入
                //控件信息载入
                this.lbAddCus.Attributes.Add("onClick", "OpenChildWinCUS()");
                this.tbGency.Attributes.Add("onClick", "new WdatePicker()");
                this.tbCustomsNo.Attributes.Add("onClick", "OpenChildWindow()");
                this.tbContainerNo.Attributes.Add("onClick", "OpenChildWindow2()");
                BindCodeData(ddlInOut, "inoutType");
                BindCodeData(ddlTradeType, "tradeType");
                BindCodeData(ddlUnit1, "unitType");
                BindCodeData(ddlUnit2, "unitType");
                BindCodeData(ddlUnit3, "unitType");
                BindCodeData(ddlgoodsType, "goodType");


                if (Request.QueryString["ID"] != null)   //修改
                {
                     SetTextBoxEnalbe(this,false );
                     SetDropDownListEnalbe(this,false);
                    int id = Convert.ToInt32(Request.QueryString["ID"]);
                    btnEdit.Enabled = false;
                    btnEdit.Visible = false;
                    btCopy.Visible = true;
                    //委托单号显示
                    lbsheet.Visible = true;
                    lbSheetValue.Text = id.ToString();
                    lbSheetValue.Visible = true;
                    edit.Visible = true;

                    ///*载入数据*/
                    CustomsSystem.Model.sheetInfo mySheetInfo = new CustomsSystem.Model.sheetInfo();//定于T_sheet表model
                    mySheetInfo = bll.GetModel(id);//获取数据
                    //   ddlTypeId.SelectedIndex = ddlTypeId.Items.IndexOf(ddlTypeId.Items.FindByValue(mySheetInfo.typeID.ToString()));//获取业务类型
                    ddlInOut.SelectedIndex = ddlInOut.Items.IndexOf(ddlInOut.Items.FindByValue(mySheetInfo.inOut.ToString()));//获取进出口类型
                    ddlTradeType.SelectedIndex = ddlTradeType.Items.IndexOf(ddlTradeType.Items.FindByValue(mySheetInfo.tradeType.ToString()));//获取贸易类型
                    ddlgoodsType.SelectedIndex = ddlgoodsType.Items.IndexOf(ddlgoodsType.Items.FindByValue(mySheetInfo.goodsType.ToString())); //货物类别的下拉框
                    ddltypeID.SelectedIndex = ddltypeID.Items.IndexOf(ddltypeID.Items.FindByValue(mySheetInfo.typeID.ToString()));//业务类别的下拉框

                    //根据公司ID获取公司名字
                    CustomerManage cusBll = new CustomerManage();
                    Customer cusModel = cusBll.GetModel(mySheetInfo.cID);
                    string cusomerName = cusModel.CustomerName;
                    tbCid.Text = cusomerName;

                    tbGency.Text = mySheetInfo.agencyDate.ToString();
                    tbGoodsName.Text = mySheetInfo.goodsName;
                    tbweight.Text = mySheetInfo.grossWeight.ToString();
                    //======提取数量====
                    string str = mySheetInfo.No;
                    string[] strArry = str.Split(',');
                    for (int i = 0; i < strArry.Length; i++)
                    {
                        //初始化数据
                        int num = 0;
                        string result1 = "";
                        string result2 = "";
                        if (strArry[i].ToString().Trim() != "")
                        {
                            num = strArry[i].IndexOf("X");
                            result1 = strArry[i].Substring(0, num);
                            result2 = strArry[i].Substring(num + 1);
                            //判断绑定数据的位置
                            if (i == 0)
                            {
                                tbCount1.Text = result1;
                                ddlUnit1.SelectedIndex = ddlUnit1.Items.IndexOf(ddlUnit1.Items.FindByText(result2));
                                continue;
                            }
                            if (i == 1)
                            {
                                tbCount2.Text = result1;
                                ddlUnit2.SelectedIndex = ddlUnit2.Items.IndexOf(ddlUnit2.Items.FindByText(result2));
                                continue;
                            }
                            if (i == 2)
                            {
                                tbCount3.Text = result1;
                                ddlUnit3.SelectedIndex = ddlUnit3.Items.IndexOf(ddlUnit3.Items.FindByText(result2));
                                continue;
                            }
                        }
                    }

                    tbCustomsNo.Text = mySheetInfo.customsNo;
                    tbInspectionNo.Text = mySheetInfo.inspectionNo;
                    tbContractNo.Text = mySheetInfo.contractNo;
                    tbAgency.Text = mySheetInfo.agency;
                    tbshipCompany.Text = mySheetInfo.shipCompany;
                    tbRemark.Text = mySheetInfo.remark;
                    tbLadingBillNo.Text = mySheetInfo.ladingBillNo;
                    tbContainerNo.Text = mySheetInfo.containerNo;
                    tbHeadBillNo.Text = mySheetInfo.headLadingBillNo;
                    tbTransferNo1.Text = mySheetInfo.transferNo1;
                    tbTransferNo2.Text = mySheetInfo.transferNo2;
                    tbTransferNo3.Text = mySheetInfo.transferNo3;
                    tbFilingNo.Text = mySheetInfo.filingNo;
                    tbInvTitle.Text = mySheetInfo.invTilte;
                    tbInspection.Text = mySheetInfo.inspetionAgancy;
                    tbPO.Text = mySheetInfo.PO.ToString();
                    tbBatchNO.Text = mySheetInfo.BatchNO.ToString();
                    tbTestItem.Text = mySheetInfo.TestItem.ToString();
                    tbModel.Text = mySheetInfo.Model.ToString();
                    tbRegUnit.Text = mySheetInfo.RegisterUnit.ToString();
                    tbTransport.Text = mySheetInfo.Transport.ToString();
                    ckDG.Checked = mySheetInfo.DangerousGoods;
                    tbshipname.Text = mySheetInfo.shipName.ToString();
                    tbgoodstype2.Text = mySheetInfo.goodsType2.ToString();
                }
                #endregion

                //新增
                else
                {
                    btnEdit.Text = "增加";
                    tbGency.Text = DateTime.Now.ToShortDateString();
                    btnEdit.Enabled = true;
                    btnEdit.Visible = true;
                }
            }
            #endregion
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {

            #region 有效性判断
            //=========有效性判断============
            string strErr = "";

            if (tbCid.Text.Trim() == "")
            {
                tbCid.BorderColor = System.Drawing.Color.Red;
                strErr += "请输入客户公司！\\n";
            }
            if (!PageValidate.IsDateTime(tbGency.Text))
            {
                tbGency.BorderColor = System.Drawing.Color.Red;
                strErr += "委托日期格式错误！\\n";
            }

            if (tbCount1.Text.Trim() != "")
            {
                if ((!PageValidate.IsDecimal(tbCount1.Text) && !PageValidate.IsNumber(tbCount1.Text)))//数量
                {
                    tbCount1.BorderColor = System.Drawing.Color.Red;
                    strErr += "数量格式错误！\\n";
                }
            }
            if (tbCount2.Text.Trim() != "")
            {
                if ((!PageValidate.IsDecimal(tbCount2.Text) && !PageValidate.IsNumber(tbCount2.Text)))//数量
                {
                    tbCount2.BorderColor = System.Drawing.Color.Red;
                    strErr += "数量格式错误！\\n";
                }
            }
            if (tbCount3.Text.Trim() != "")
            {
                if ((!PageValidate.IsDecimal(tbCount3.Text) && !PageValidate.IsNumber(tbCount3.Text)))//数量
                {
                    tbCount3.BorderColor = System.Drawing.Color.Red;
                    strErr += "数量格式错误！\\n";
                }
            }
            if (tbweight.Text.Trim() != "")
            {
                if ((!PageValidate.IsDecimal(tbweight.Text) && !PageValidate.IsNumber(tbweight.Text)))//数量
                {
                    tbweight.BorderColor = System.Drawing.Color.Red;
                    strErr += "毛重格式错误！\\n";
                }
            }

            //重复判断
            if (this.tbTransferNo3.Text.Trim().Length != 0)
            {
                if (tbTransferNo1.Text.Trim().Length == 0)
                {
                    if (tbTransferNo2.Text.Trim().Equals(tbTransferNo3.Text.Trim()))
                        strErr += "移交号不能重复！\\n";
                }
                else if (tbTransferNo1.Text.Trim().Equals(tbTransferNo2.Text.Trim()) || tbTransferNo2.Text.Trim().Equals(tbTransferNo3.Text.Trim()) || tbTransferNo1.Text.Trim().Equals(tbTransferNo3.Text.Trim()))
                    strErr += "移交号不能重复！\\n";
            }
            else if (this.tbTransferNo2.Text.Trim().Length != 0)
            {
                if (tbTransferNo1.Text.Trim().Equals(tbTransferNo2.Text.Trim()))
                    strErr += "移交号不能重复！\\n";
            }
            if (this.tbLadingBillNo.Text.Trim().Length == 0)
            {
                tbLadingBillNo.BorderColor = System.Drawing.Color.Red;
                strErr += "提单号不能为空！\\n";
            }
            if (tbContainerNo.Text.Trim().Length >= 1000)
            {
                tbContainerNo.BorderColor = System.Drawing.Color.Red;
                strErr += "柜号字数超过长度！\\n";
            }
            if (tbRemark.Text.Trim().Length >= 240)
            {
                tbRemark.BorderColor = System.Drawing.Color.Red;
                strErr += "备注字数超过规定长度！\\n";
            }
            if (tbCustomsNo.Text.Trim().Length >= 450)
            {
                strErr += "报关单号字数超过规定长度！\\n";
                tbCustomsNo.BorderColor = System.Drawing.Color.Red;
            }
            #endregion

            //错误信息的显示
            if (strErr != "")
            {
                MessageBox.Show(this, strErr);
                return;
            }

            #region 信息的录入

            //信息录入
            CustomsSystem.Model.sheetInfo mySheetInfo = new CustomsSystem.Model.sheetInfo();

            //判断是否为修改
            int sheetID = Convert.ToInt32(lbSheetValue.Text.ToString().Trim());//读取判断的委托单号
            if (sheetID.ToString() != "0")
            {
                mySheetInfo = bll.GetModel(sheetID);
            }
            mySheetInfo.sheetID = sheetID;
            // mySheetInfo.typeID = Convert.ToInt32(ddlTypeId.SelectedValue);
            mySheetInfo.inOut = Convert.ToInt32(ddlInOut.SelectedValue);
            mySheetInfo.tradeType = Convert.ToInt32(ddlTradeType.SelectedValue);
            mySheetInfo.goodsType = Convert.ToInt32(ddlgoodsType.SelectedValue);
            mySheetInfo.typeID = Convert.ToInt32(ddltypeID.SelectedValue);
            if (tbweight.Text.ToString().Trim() != "")
            {
                mySheetInfo.grossWeight = Convert.ToDecimal(tbweight.Text);
            } 

            #region 公司号，货物号的提取

            //根据公司名字获取公司ID
            CustomerManage cusBll = new CustomerManage();
            List<Customer> cusModels = cusBll.GetModelList("CustomerName='" + tbCid.Text.Trim() + "'");
            int cusID;
            if (cusModels.Count != 0)
            {
                cusID = cusModels[0].ID;
            }
            else
            {
                cusID = 0;
                MessageBox.Show(this, "该公司不存在，请确认"); //error["cusID"] = "该公司不存在，请确认";
                return;
            }

            mySheetInfo.cID = cusID;

            //==========根据模板取货物ID===============

            //WorkflowManage wfMan = new WorkflowManage();
            //Info_workflowMaster model;
            //if (ddlworkflowInfo.SelectedValue != "-1")
            //{
            //    model = wfMan.GetModelMaster(Convert.ToInt32(ddlworkflowInfo.SelectedValue));
            //}
            //else
            //{
            //    model = wfMan.GetModelMaster(Convert.ToInt32(ddlworkflowInfoBJ.SelectedValue));
            //}

            //int goodstype = 0;
            //if (model.goodsTypeID != null) goodstype = (int)model.goodsTypeID;
            //mySheetInfo.goodsType = goodstype;

            #endregion

            mySheetInfo.agencyDate = Convert.ToDateTime(tbGency.Text.Trim()).Date;
            mySheetInfo.goodsName = tbGoodsName.Text.Trim();
            mySheetInfo.No = GetCount();
            mySheetInfo.shipName = tbshipname.Text.Trim();

            if (tbCustomsNo.Text.Trim() != "")
                mySheetInfo.customsNo = tbCustomsNo.Text.Trim();

            if (tbInspectionNo.Text.Trim() != "")
                mySheetInfo.inspectionNo = tbInspectionNo.Text.Trim();

            mySheetInfo.contractNo = tbContractNo.Text.Trim();
            mySheetInfo.agency = tbAgency.Text.Trim();
            mySheetInfo.shipCompany = tbshipCompany.Text;
            mySheetInfo.remark = tbRemark.Text;


            mySheetInfo.ladingBillNo = tbLadingBillNo.Text.Trim();
            mySheetInfo.containerNo = tbContainerNo.Text.Trim();
            mySheetInfo.headLadingBillNo = tbHeadBillNo.Text.Trim();


            if (tbTransferNo1.Text.Trim() != "")
                mySheetInfo.transferNo1 = tbTransferNo1.Text.Trim();

            if (tbTransferNo2.Text.Trim() != "")
                mySheetInfo.transferNo2 = tbTransferNo2.Text.Trim();

            if (tbTransferNo3.Text.Trim() != "")
                mySheetInfo.transferNo3 = tbTransferNo3.Text.Trim();


            mySheetInfo.filingNo = tbFilingNo.Text.Trim();
            mySheetInfo.invTilte = tbInvTitle.Text.Trim();
            mySheetInfo.inspetionAgancy = tbInspection.Text.Trim();
            mySheetInfo.PO = tbPO.Text.Trim();
            mySheetInfo.BatchNO = tbBatchNO.Text.Trim();
            mySheetInfo.TestItem = tbTestItem.Text.Trim();
            mySheetInfo.Model = tbModel.Text.Trim();
            mySheetInfo.RegisterUnit = tbRegUnit.Text.Trim();
            mySheetInfo.Transport = tbTransport.Text.Trim();
            mySheetInfo.DangerousGoods = ckDG.Checked;
            mySheetInfo.tradeType = Convert.ToInt32(ddlTradeType.SelectedValue);
            mySheetInfo.goodsType2 = tbgoodstype2.Text.Trim();
            if (mySheetInfo.sheetID <= 0)//增加记录
            {
                #region 模板类型
                mySheetInfo.InfoWKTypeIDbg = 47;//这里需要修改
                mySheetInfo.InfoWKTypeIDbj = -1;//-1为没有模板
                #endregion
                mySheetInfo.inputEmpNo = Session["EmpNo"].ToString();
                mySheetInfo.inputDate = DateTime.Now;
                int newid = bll.Add(mySheetInfo);
                int sheetid = bll.GetMaxId() - 1;

                if (newid > 0)
                {
                    sheetWorkflowStart sw = new sheetWorkflowStart();//启动工作流
                    sw.WorkflowStart(sheetid);
                    MessageBox.Show(this, "增加成功");

                }
                else
                { MessageBox.Show(this, "增加失败"); }
            }
            else     //修改记录
            {
                if (bll.Update(mySheetInfo))
                {
                    MessageBox.ShowAndRedirect(this, "修改成功", "sheetView.aspx");
                }
                else
                { MessageBox.Show(this, "修改失败"); }
            }

            #endregion
        }

        #region  信息的处理

        /// <summary>
        /// 获取制定代码类型绑定到控件上
        /// </summary>
        /// <param name="ddl"></param>
        private void BindCodeData(DropDownList ddl, string codeType)
        {
            CodeManage codeBll = new CodeManage();
            List<Info_code> codeModels = codeBll.GetModelList("codeType='" + codeType + "'");
            foreach (Info_code aCode in codeModels)
            {
                ddl.Items.Add(new ListItem(aCode.codeName, aCode.codeID.ToString()));
            }
        }
        ///// <summary>
        ///// 获取所有工作流模板
        ///// </summary>
        ///// <param name="ddl"></param>
        //private void BindFlowInfo(DropDownList ddl, int type)
        //{
        //    WorkflowManage wfBll = new WorkflowManage();
        //    List<Info_workflowMaster> wfModels = wfBll.GetModelListMaster("");
        //    foreach (Info_workflowMaster aflow in wfModels)
        //    {
        //        if (aflow.sheetTypeID == type && aflow.States != 2)
        //            ddl.Items.Add(new ListItem(aflow.WKTypeName, aflow.infoWKTypeID.ToString()));
        //    }
        //}

        [System.Web.Services.WebMethod]
        [System.Web.Script.Services.ScriptMethod]
        public static string[] GetCustomersName(string prefixText, int count)
        {
            CustomerManage cusManage = new CustomerManage();
            List<string> strArray = new List<string>();
            //string[] strArray = { "中国石油公司","中顺洁柔","中山技术",
            //"捷达捷达捷达达","时代复分","幅度为爱"};
            List<Customer> cusList = cusManage.GetModelList("");
            foreach (Customer aCus in cusList)
            {
                strArray.Add(aCus.CustomerName);
            }
            return (from m in strArray
                    where m.Contains(prefixText)
                    select m).Take(count).ToArray();
        }
        /// <summary>
        /// 获取数量值
        /// </summary>
        /// <returns></returns>
        public string GetCount()
        {
            string count = "";

            if (tbCount1.Text.Trim() != "")
            {
                count = tbCount1.Text + "X" + ddlUnit1.SelectedItem.Text;
                if (tbCount2.Text.Trim() != "")
                {
                    count = count + "," + tbCount2.Text + "X" + ddlUnit2.SelectedItem.Text;
                    if (tbCount3.Text.Trim() != "")
                    {
                        count = count + "," + tbCount3.Text + "X" + ddlUnit3.SelectedItem.Text;
                    }
                }
            }
            return count;
        }
        /// <summary>
        /// 公司的名
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void tbCid_TextChanged(object sender, EventArgs e)
        {
            atuoBack();
        }
        /// <summary>
        /// 获取工作要求
        /// </summary>
        public void atuoBack()
        {
            CustomerManage cusBll = new CustomerManage();
            List<Customer> cusModels = cusBll.GetModelList("CustomerName='" + tbCid.Text.Trim() + "'");
            if (cusModels.Count != 0)
            {
                tbInvTitle.Text = cusModels[0].Invoice;
                if (cusModels[0].Remarks != "")
                    lbRemark.Text = "工作要求：</br>" + cusModels[0].Remarks;
                lbRemark.Visible = true;//显示要求
            }
        }
        #endregion

        /// <summary>
        /// 复制键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Copy_Click(object sender, EventArgs e)
        {
            SetTextBoxEnalbe(this, true);
            SetDropDownListEnalbe(this, true);
            lbsheet.Visible = false;
            edit.Visible = false;
            edit.Enabled = false;
            lbSheetValue.Text = "0";//0为增加，大于0为修改
            lbSheetValue.Visible = false;//修改委托单号信息，用于增加按钮的判断
            btnEdit.Text = "增加";
            btnEdit.Visible = true;
            btnEdit.Enabled = true;
            btCopy.Visible = false;
            MessageBox.Show(this, "复制成功！");

        }

        protected void Edit_Click(object sender, EventArgs e)
        {
             SetTextBoxEnalbe(this,true);
             SetDropDownListEnalbe(this, true);
             btnEdit.Text = "修改";
             btnEdit.Enabled = true;
             btnEdit.Visible = true;
        }
          public void SetTextBoxEnalbe(Control control, bool enable)  
         {  
                if (control is TextBox)  
                {  
                    (control as TextBox).Enabled = enable;  
                }  
                else if (control.HasControls())  
                {  
                    foreach (System.Web.UI.Control s in control.Controls)  
                    {  
                        if (s is TextBox)  
                        {  
                            (s as TextBox).Enabled = enable;  
                        }  
                        else if (s.HasControls())  
                        {  
                            SetTextBoxEnalbe(s, enable);  
                        }  
                    }  
                }  
            }
          public void SetDropDownListEnalbe(Control control, bool enable)
          {
              if (control is DropDownList )
              {
                  (control as DropDownList).Enabled = enable;
              }
              else if (control.HasControls())
              {
                  foreach (System.Web.UI.Control s in control.Controls)
                  {
                      if (s is DropDownList)
                      {
                          (s as DropDownList).Enabled = enable;
                      }
                      else if (s.HasControls())
                      {
                          SetDropDownListEnalbe(s, enable);
                      }
                  }
              }
          }  
        }



    }
